/*************  云函数  ***********/
const app = getApp()

const db = wx.cloud.database();

module.exports = {
  // 获取openid
  getOpenId: () => {
    return wx.cloud.callFunction({
      name: "getOpenId"
    })
  },
  // 上传当日到家定位信息
  uploadLocation: (latitude, longitude) => {
    return wx.cloud.callFunction({
      name: "uploadLocation",
      data: {
        latitude: latitude,
        longitude: longitude
      }
    })
  },

  getTodayCourseInfo: async function() {
    let res = await db.collection('tb_schedule')
      .where({
        date: new Date().toLocaleDateString().replace(/\//g, '-'),
        _openid: app.globalData.openId,
      })
      .get()
    return res
  },


  // 判断今日是否已经上传定位信息
  hasUploadLocation: async() => {
    let res = await db.collection('tb_schedule')
      .where({
        date: new Date().toLocaleDateString().replace(/\//g, '-'),
        _openid: app.globalData.openId,
      })
      .count()

    return Boolean(res.total)
  },

  // 更新课程信息
  uploadCourse: async function(key, value, isSelf = false) {
    let res = await wx.cloud.callFunction({
      name: "updateCourseInfo",
      data: {
        key: key,
        data: value,
        isSelf
      }
    })
    return Boolean(res && res.result && res.result.stats)
  },

  getWeekStatistics: async function() {
    let res = await wx.cloud.callFunction({
      name: 'getWeekStudyTime',
      data: {
        isSelf: true
      }
    })
    return res.result
  },

  async getCourseTimeOfWeeks(courseName) {
    let res = await wx.cloud.callFunction({
      name: 'getCourseTimeOfWeeks',
      data: {
        course: courseName
      }
    });
    return res
  },

  async getDayStudyTimeOfWeeks() {
    let res = await wx.cloud.callFunction({
      name: 'getDayStudyTimeOfWeeks'
    });
    return res
  },

  async getScores() {
    let res;
    try {
      res = await db.collection('tb_score')
        .where({
          _openid: app.globalData.openId
        })
        .orderBy('date', 'desc')
        .get()
    } catch (e) {}
    return res.data
  },

  async addScoreRecord(data) {
    let total = 0;
    for(let key in data){
      total += data[key]
    }
    Object.assign(data, {
      date: new Date().toLocaleDateString().replace(/\//g, '-'),
      total
    })
    let res;
    try {
      res = await db.collection('tb_score').add({
        data
      })
    } catch (e) {}
    return res
  }
}